import { GameModel, GameState } from './game-model.js';
import { GameView } from './game-view.js';

class GamePresenter {
    constructor() {
        this.model = new GameModel();
        this.view = new GameView();
        this.bindViewHandlers();
    }

    initialize() {
        this.view.showLoading();
        try {
            this.model.initialize();
            this.view.hideLoading();
            this.view.showAttributeSelection();
        } catch (error) {
            console.error('游戏初始化失败:', error);
            this.view.logMessage('游戏初始化失败，请刷新页面重试');
        }
    }

    bindViewHandlers() {
        this.view.onAttributeSelect = (attribute) => this.handleAttributeSelection(attribute);
        this.view.onPhaseEnd = () => this.handlePhaseEnd();
        this.view.onSurrender = () => this.handleSurrender();
        this.view.onCardSelect = (card) => this.handleCardSelect(card);
        this.view.onMonsterSelect = (monster) => this.handleMonsterSelect(monster);
        this.view.onMagicSelect = (magic) => this.handleMagicSelect(magic);
        this.view.onDirectAttack = () => this.handleDirectAttack();
    }

    async handleAttributeSelection(attribute) {
        this.view.hideAttributeSelection();
        
        try {
            await Promise.all([
                this.model.initializePlayerDeck(attribute),
                this.model.initializeRobotDeck()
            ]);
            
            this.model.currentPlayer = this.model.player;
            this.model.currentState = GameState.DRAWING;
            this.updateView();
            this.startTurn();
        } catch (error) {
            console.error('卡组初始化失败:', error);
            this.view.logMessage('卡组初始化失败，请刷新页面重试');
        }
    }

    async startTurn() {
        const isBot = this.model.currentPlayer.isBot;
        this.view.logMessage(`${isBot ? '机器人' : '玩家'}的回合开始`);
        
        const drawResult = this.model.currentPlayer.drawCard();
        if (drawResult.success) {
            this.view.logMessage(`抽到了 ${drawResult.card.name}`);
        } else {
            this.view.logMessage(drawResult.message);
            if (drawResult.message === '卡组已空') {
                this.endGame(isBot ? '玩家' : '机器人');
                return;
            }
        }

        this.model.currentState = GameState.PLACING;
        this.view.logMessage('进入放置阶段');
        this.updateView();

        if (isBot) {
            await this.model.executeBotTurn();
            this.handlePhaseEnd();
        }
    }

    handlePhaseEnd() {
        switch (this.model.currentState) {
            case GameState.PLACING:
                this.model.currentState = GameState.BATTLE;
                this.view.logMessage('进入战斗阶段');
                break;
            case GameState.BATTLE:
                this.model.switchTurn();
                this.startTurn();
                break;
        }
        this.updateView();
    }

    handleSurrender() {
        this.endGame('机器人');
    }

    handleCardSelect(card, position) {
        if (this.model.currentState !== GameState.PLACING) return;

        if (card.type === 'monster') {
            const result = this.model.placeCard(card, 'monster', position);
            if (!result) {
                this.view.showMessage('无法放置卡牌', 'error');
            }
        } else {
            const result = this.model.placeCard(card, 'magic');
            if (!result) {
                this.view.showMessage('无法放置卡牌', 'error');
            }
        }
        this.updateView();
    }

    handleMonsterSelect(monster) {
        if (this.model.currentState !== GameState.BATTLE) return;

        if (!this.selectedMonster) {
            // 第一次选择，选中攻击方
            if (monster.canAttack) {
                this.selectedMonster = monster;
                this.view.selectCard(event.target);
                
                // 检查是否可以直接攻击
                const canDirectAttack = this.model.robot.monsterZone.length === 0;
                this.view.enableBattleTargets(canDirectAttack);
            } else {
                this.view.showMessage('这个怪兽本回合已经攻击过了', 'error');
            }
        } else {
            // 第二次选择，选中防守方
            const result = this.model.battle(this.selectedMonster, monster);
            if (result.success) {
                this.view.logMessage(result.message);
                if (result.gameOver) {
                    this.endGame(result.winner);
                }
            } else {
                this.view.showMessage(result.message, 'error');
            }
            
            this.selectedMonster = null;
            this.view.clearSelection();
            this.view.disableBattleTargets();
            this.updateView();
        }
    }

    handleMagicSelect(magic) {
        if (this.model.currentState !== GameState.BATTLE) return;

        if (!this.selectedMagic) {
            // 第一次选择，选中魔法卡
            this.selectedMagic = magic;
            this.view.selectCard(event.target);
            
            // 启用所有怪兽区域的点击
            const allMonsters = [
                ...this.model.player.monsterZone,
                ...this.model.robot.monsterZone
            ];
            allMonsters.forEach(monster => {
                if (monster.position === 'attack') {
                    this.view.markCardAsAttackable(
                        document.querySelector(`[data-card-id="${monster.id}"]`)
                    );
                }
            });
        } else {
            // 第二次选择，选中目标怪兽
            const result = this.model.activateMagicCard(this.selectedMagic, magic);
            if (result.success) {
                this.view.logMessage(result.message);
            } else {
                this.view.showMessage(result.message, 'error');
            }
            
            this.selectedMagic = null;
            this.view.clearSelection();
            this.view.unmarkAllCards();
            this.updateView();
        }
    }

    handleDirectAttack() {
        if (!this.selectedMonster) return;

        const result = this.model.directAttack(this.selectedMonster);
        if (result.success) {
            this.view.logMessage(result.message);
            if (result.gameOver) {
                this.endGame(result.winner);
            }
        } else {
            this.view.showMessage(result.message, 'error');
        }
        
        this.selectedMonster = null;
        this.view.clearSelection();
        this.view.disableBattleTargets();
        this.updateView();
    }

    updateView() {
        this.view.updateLifePoints('player', this.model.player.lifePoints);
        this.view.updateLifePoints('robot', this.model.robot.lifePoints);
        
        const gameState = {
            playerHand: this.model.player.hand,
            playerMonsterZone: this.model.player.monsterZone,
            playerMagicZone: this.model.player.magicZone,
            robotHand: this.model.robot.hand,
            robotMonsterZone: this.model.robot.monsterZone,
            robotMagicZone: this.model.robot.magicZone,
            playerDeckCount: this.model.player.deck.length,
            robotDeckCount: this.model.robot.deck.length,
            playerGraveyardCount: this.model.player.graveyard.length,
            robotGraveyardCount: this.model.robot.graveyard.length
        };

        this.view.updateCardZones(gameState);
        this.view.enableControls(this.model.currentState.toLowerCase());
    }

    checkGameEnd() {
        const result = this.model.checkGameEnd();
        if (result.gameOver) {
            this.endGame(result.winner);
        }
    }

    endGame(winner) {
        this.view.logMessage(`游戏结束！${winner}获得胜利！`);
        const resultDiv = this.view.showGameResult(winner);
        
        setTimeout(() => {
            resultDiv.remove();
            this.initialize();
        }, 3000);
    }
}

// 初始化游戏
document.addEventListener('DOMContentLoaded', () => {
    try {
        const gamePresenter = new GamePresenter();
        gamePresenter.initialize();
    } catch (error) {
        console.error('游戏创建失败:', error);
        alert('游戏加载失败，请刷新页面重试');
    }
});

export { GamePresenter };
